package com.jiubanqingchen.future.org.admin;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.jfinal.core.Controller;
import com.jfinal.core.NotAction;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.jiubanqingchen.future.common.enums.SystemStatus;
import com.jiubanqingchen.future.common.tool.StrTool;
import com.jiubanqingchen.future.model.models.User;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author Light_Dust
 * @ClassName: BaseController
 * @Description: (公共controller)
 * @date 2019年7月4日 下午1:46:51
 */
public class BaseController extends Controller implements IBaseController {

    @Override
    @NotAction
    public void renderResult(Object obj) {
        renderJson(new Json(obj));
    }


    @Override
    @NotAction
    public void renderResult(SystemStatus systemStatus) {
        renderJson(new Json(systemStatus.getCode(), systemStatus.getMsg()));

    }


    @Override
    @NotAction
    public void renderResult(SystemStatus systemStatus, Object obj) {
        renderJson(new Json(systemStatus.getCode(), systemStatus.getMsg(), obj));
    }

    @Override
    @NotAction
    /**
     * 获取额外参数 一般传输json数据 但是也会有一些额外参数
     */
    public Record getRecordExtData() {
        Map<String, String[]> params = getParaMap();
        if (params != null) {
            Record record = new Record();
            for (Map.Entry<String, String[]> entry : params.entrySet()) {
                String value = StrTool.arrayToString(entry.getValue());
                if (StrKit.notBlank(value)) {
                    record.set(entry.getKey(), value);
                }
            }
            return record;
        }
        return null;
    }

    @Override
    @NotAction
    /**
     * 获取json数据
     */
    public Record getRecordRawData() {
        Map<String, Object> mapData = getRawDataForObject(Map.class);
        return mapData == null ? null : new Record().setColumns(mapData);
    }

    @Override
    @SuppressWarnings("unchecked")
    @NotAction
    public <T> T getRawDataForObject(Class<?> clazz) {
        if (StrKit.notBlank(getRawData())) {
            return (T) JsonKit.parse(getRawData(), clazz);
        }
        return null;
    }

    @Override
    @NotAction
    public Model getRawDataForModel(Class<?> clazz) {
        return (Model) getRawDataForObject(clazz);
    }

    @Override
    @SuppressWarnings("unchecked")
    @NotAction
    public <T> List<T> getRawDataForArray(Class<?> clazz) {
        if (StrKit.notBlank(getRawData())) {
            return (List<T>) JSON.parseArray(getRawData(), clazz);
        }
        return null;
    }

    @Override
    @NotAction
    public <T> List<Model<?>> getRawDataForModelArray(Class<?> clazz) {
        String rawData=getRawData();
        return  StrKit.notBlank(rawData)?(List<Model<?>>) JSON.parseArray(getRawData(), clazz):null;
    }

    public Kv getRawDataForKv(){
        String rawData=getRawData();
        return StrKit.notBlank(rawData)?JsonKit.parse(rawData,Kv.class):null;
    }

    @Override
    @NotAction
    public String getCurrentToken() {
        return getHeader("Access-Token");
    }


    @Override
    @NotAction
    public User getCurrentUser() {
        return JsonKit.parse(JsonKit.toJson(getSessionAttr("currentUser")), User.class);
    }

    @NotAction
    /**
     * @param fileName 文件下载名称
     * @param clazz 导出bean
     * @param sheetName sheetName
     * @param data 导出数据
     */
    public void downloadExcel(String fileName, Class<?> clazz, String sheetName, List<?> data) throws Exception {
        HttpServletResponse response = getResponse();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        fileName = URLEncoder.encode(fileName, "UTF-8"); // 这里URLEncoder.encode可以防止中文乱码
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        response.setHeader("filename", fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(data);
        renderNull();
    }
}
